import { computed, onMounted, ref } from "vue";
import { getSwiper } from "@/api/api";
import { getUserInfo } from "@/api/user/user";
import { useUserStore } from "@/store";
import { useRouter } from "vue-router";
import { showNotify } from "vant";
import { showConfirmDialog } from "vant";

//mys 组件逻辑
export const useMysHandler = () => {
  const userStore = useUserStore();
  const userid = userStore.userid;
  const token = userStore.token;
  const username = ref("");
  const userIcon = ref("");
  const flag = computed(() => {
    if (token && userid) {
      return false;
    } else {
      return true;
    }
  });

  const coffeeWallet = computed(() => {
    if (username && token) return "/coffeewallet";
    else return "/login";
  });
  const person = computed(() => {
    if (username && token) return "/personal";
    else return "/login";
  });

  const coupon = computed(() => {
    if (username && token) return "/coupon";
    else return "/login";
  });
  const offers = computed(() => {
    if (username && token) return "/redeemtheoffer";
    else return "/login";
  });

  const userInfo = async () => {
    let res = await getUserInfo({ id: userid });
    if (res.data instanceof Array) {
      username.value = res.data[0].username;
      userIcon.value = res.data[0].header_img;
    }
  };

  onMounted(() => {
    userInfo();
  });

  return {
    username,
    flag,
    coffeeWallet,
    person,
    coupon,
    offers,
    userIcon
  };
};

//person组件逻辑

export const usePersonHandler = () => {
  const router = useRouter();
  const userStore = useUserStore();
  const username = ref();
  const userid = userStore.userid;
  const tel = ref();
  const userInfo = async () => {
    let res = await getUserInfo({ id: userid });
    tel.value = res.data[0].tel;
    username.value = res.data[0].username;
  };
  onMounted(() => {
    userInfo();
  });
  const logOut = () => {
    showConfirmDialog({
      title: "退出登录",
      message: "你确定要退出登录吗",
    })
      .then(() => {
        showNotify({ type: "success", message: "退出账号" });
        userStore.removeUserInfo();
        router.replace("/home");
      })
      .catch(() => {
        return;
      });
  };

  return {
    username,
    tel,
    logOut,
    userid,
  };
};

//acounts组件
export const useAcountsHandler = () => {
  const swipe = ref([]);
  onMounted(() => {
    swipeList();
  });
  const swipeList = async () => {
    let { data } = await getSwiper();
    swipe.value = data;
  };

  return {
    swipe,
  };
};
